package com.s64.ch08.modules.token;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.s64.ch08.modules.security.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class DefaultTokenService implements TokenService {
    private final StringRedisTemplate stringRedisTemplate;
    private final ObjectMapper objectMapper;

    @Override
    @SneakyThrows
    public Token createToken(LoginUser loginUser) {
        String uuid = UUID.randomUUID().toString();
        Token token = new Token(uuid, loginUser.getUser().getNickName());
        stringRedisTemplate.opsForValue().set("s64:login:" + uuid, objectMapper.writeValueAsString(loginUser), Duration.ofMinutes(10));
        return token;
    }

    @Override
    public boolean removeToken(String token) {
        return stringRedisTemplate.delete("s64:login:" + token);
    }

    @Override
    @SneakyThrows
    public LoginUser getLoginUser(String token) {
        String json = stringRedisTemplate.opsForValue().get("s64:login:" + token);
        if (StringUtils.hasText(json)) {
            return objectMapper.readValue(json, LoginUser.class);
        }
        return null;
    }
}
